<?php
//Include product arrays
include 'product_data.inc';

//Include functions that are defined
include 'functions.inc';
$all_users=  arrayfile_to_array('./user_data.dat');

//If the user clicks the log in button, I want to validate the input info.
if (array_key_exists('login', $_POST)) {
    if ($actual_user_key=array_key_exists_nc($_POST['username'], $all_users)) {
        //found the user, now go get user information.
        $user_info = $all_users[$actual_user_key];
        if ($user_info['password'] == $_POST['password']) {
            echo 'Welcome ' . $_POST['username'] . ".";
            echo "<br>";
            // lets just make this another form with the quantities in it to pass to invoice.php

            print "<form action ='invoice.php' method='post'>";
            // this will take the quantity data and store it in the form as hidden and pass it to invoice.php
            for ($i = 0; $i < count($products); $i++) {
                $qty = $_POST["quantity$i"];
                print "<input type=hidden name=quantity$i value=$qty>";
            }
            // put the username in the form, so the invoice knows who the user is
                print "<input type=hidden name=username value=$actual_user_key>";
            // make a submit button for this new form rather than a hyperlink
            echo "<input type=submit value='Click here to continue to your shopping cart'>";
            exit ();
        } else {
            echo "Please check your password or ";
            ?><a href='registration.php'>register here!</a><?php

        }
    }
} else {
    echo "Please log in or ";
    echo "<a href='registration.php'>register here!</a>";
    echo "<br><br>";
}
//check to see if username doesn't exist
if(array_key_exists('login',$_POST)){
    if(!array_key_exists($_POST['username'],$all_users)){
        echo "Please log in or ";
        echo "<a href='registration.php'>register here!</a>";
    }
} 
?>            
<form action ='<?php echo $_SERVER['PHP_SELF'] ?>' method="post">
    Username: <br>
    <input type="text" name="username" value="<?php if (isset($_POST['username'])) echo $_POST['username'] ?>"><br>
    Password: <br>
    <input type="password" name="password">
    <input type= 'submit' name= 'login' value= 'log in'>
    <?php
// this will take the quantity data from the original post and keep it while the user tries to login
    for ($i = 0; $i < count($products); $i++) {
        $qty = $_POST["quantity$i"];
        print "<input type=hidden name=quantity$i value=$qty>";
    }
    ?>

</form>